<?php

/**
 * Calls response via API depending on the requested method
 * Note: This is used on post_request_api()
 * @author GeoffreyEmbuscado 02.11.2015
 * @param $method, $url, $data
 * @return String
 */
function call_api( $method, $url, $data = false ) {

	// Method: POST, PUT, GET etc
	// Data: array('param' => 'value') -> index.php?param=value
	$curl = curl_init();

	switch ($method)
	{
		case 'POST':
			curl_setopt($curl, CURLOPT_POST, 1);

			if ( $data ) curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  
			break;
		case 'PUT':
			curl_setopt($curl, CURLOPT_PUT, 1);
			break;
		default:
			if ( $data ) $url = sprintf('%s?%s', $url, http_build_query($data));
	}

	// Optional Authentication:
	curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	curl_setopt($curl, CURLOPT_USERPWD, "username:password");

	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

	$result = curl_exec($curl);

	curl_close($curl);

	return $result;
}

/**
 * Simplified API for call_api using POST Method
 * This function uses call_api()
 * This function is still under going
 * @author GeoffreyEmbuscado 02.11.2015
 * @return String
 */
function post_request_api() {
}

/**
 * Simplified API for call_api using GET Method
 * This function uses call_api()
 * @author GeoffreyEmbuscado 02.11.2015
 * @param $route, $dynamic_route
 * @return String
 */
function get_request_api( $route = '', $dynamic_route = array() ) {
	$route = $route;
	
	if( count($dynamic_route) > 0 ){
		$route .= '/' . implode('/', $dynamic_route);
	}
	
	$data = json_decode(call_api('GET', Config::get('app.api') . $route));
	return $data;
}